/*
 *  *****************************************************************************
 *  * Copyright (C) 2022 szjzsoft Co.,Ltd
 *  * All Rights Reserved.
 *  * 本软件为深圳市金政软件技术有限公司（平台）研制。未经本公司正式书面同意，其他任何个人、团体
 *  * 不得使用、复制、修改或发布本软件.
 *  ****************************************************************************
 */

package cc.bookcloud.tool.ocr.controller;

import cc.bookcloud.tool.ocr.common.JResult;
import cc.bookcloud.tool.ocr.common.dirs.FsRequVo;
import cc.bookcloud.tool.ocr.common.dirs.FsUnit;
import cc.bookcloud.tool.ocr.common.dirs.ReqParamConstant;
import cc.bookcloud.tool.ocr.common.sqlite.Sqlite3Client;
import cc.bookcloud.tool.ocr.util.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.env.Environment;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * @Desc: 目录服务
 * @version: 2.0
 * @author: John Goo
 * @date: 2022/04/27 13:58
 **/
@Slf4j
@RestController
@Api(tags = "一体化编译发版辅助小工具-目录服务", value = "一体化编译发版辅助小工具-目录服务")
@RequestMapping("/release")
public class DirServiceController {

    // 默认目录
    public static final String _DIR_DEFAULT = "/SZJZ/";


    @Resource
    private Environment environment;


    @Resource
    private Sqlite3Client sqlite3Client;


    @ApiOperation(value = "进入文件目录服务")
    @GetMapping("/fs/go")
    public ModelAndView goFs(HttpServletRequest request){
        ModelAndView view = new ModelAndView("pages/filedir-service");
        return view;
    }

    /**
     * @param request
     * @return ModelAndView
     * @desc：文件目录访问服务
     * @author：yourName
     * @date：2022/4/28 9:17
     */
    @ApiOperation(value = "文件目录服务")
    @GetMapping("/fs/list")
    public JResult<FsRequVo> iteratorDir(HttpServletRequest request) {
        JResult result = JResult.build();
        FsRequVo fsVo = new FsRequVo();
        String servletPath = request.getServletPath();
        String matchURI = (String) request.getSession().getAttribute(ReqParamConstant.REQ_URI);
        String fsPath = (String) request.getSession().getAttribute(ReqParamConstant.REQ_FS_PATH);
        fsVo.setCurrentDir(matchURI);
        String parentDir = StringUtil.extractParent(matchURI);

        fsVo.setParentDir(parentDir);
        File file = new File(fsPath);
        File[] files = file.listFiles();
        List fileList = new ArrayList<>();
        if (files != null) {
            for (File fileItem : files) {
                // 存储对象
                FsUnit fileMeta = new FsUnit();
                String fileName;
                // 目录
                if (fileItem.isDirectory()) {
                    fileName = fileItem.getName() + "/";
                    fileMeta.setDescription("--");
                    // 目录
                    fileMeta.setIsDir(1);
                    // 文件
                } else {
                    fileName = fileItem.getName();
                    fileMeta.setDescription("下 载");
                    // 文件
                    fileMeta.setIsDir(0);
                }
                fileMeta.setFileName(fileName);
                fileMeta.setSize(fileItem.length() + " bytes");
                // 修改时间
                SimpleDateFormat sf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
                fileMeta.setLastModified(sf.format(fileItem.lastModified()));
                // 相对路径
                if (!matchURI.endsWith("/")) {
                    matchURI = matchURI + "/";
                }
                String relative = matchURI + fileName;
                fileMeta.setRelativePath(relative);
                fileList.add(fileMeta);
                fsVo.setFsList(fileList);
            }
        }
        // 传到前端值
        result.ok(fsVo);
        return result;
    }


    /**
     * @param request
     * @param resp
     * @return void
     * @desc：目录服务-文件下载
     * @author：yourName
     * @date：2022/4/28 9:41
     */
    @ApiOperation(value = "目录服务-下载")
    @GetMapping("/fs/download")
    public void download(HttpServletRequest request, HttpServletResponse resp) {
        // 请求传参数，/fd/download?filePath=/
        String relativePath = request.getParameter("relativePath");
        // String deStr = URLDecoder.decode(requestParameter, "UTF-8");

        // 根路径
        String rootDir = environment.getProperty("fs.dir");
        if (StringUtil.isEmpty(relativePath)) {
            // 提示参数输入不正确
            return;
        }
        // 完整文件路径
        // String filePath = rootDir + relativePath;
        String filePath = relativePath.replace(ReqParamConstant.DS_FIXED_URI, rootDir);
        File file = new File(filePath);
        FastByteArrayOutputStream fbos = null;
        ServletOutputStream out = null;
        InputStream is = null;
        try {
            out = resp.getOutputStream();
            resp.reset();
            resp.setCharacterEncoding("UTF-8");
            resp.setContentType("application/octet-stream");
            resp.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
            byte[] buf = new byte[1024];
            int len = 0;
            is = new FileInputStream(file);
            log.info("文件大小：" + is.available());
            while ((len = is.read(buf)) != -1) {
                out.write(buf, 0, len);
            }
            out.flush();

        } catch (Exception e) {
            log.error("[目录服务]下载文件发生了异常！", e);
        } finally {
            try {
                if (fbos != null) {
                    fbos.close();
                }
                if (is != null) {
                    is.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                log.error("[目录服务]下载文件发生了异常！", e);
            }
        }

    }


}
